import Vue from 'vue'
import Vuex from 'vuex'

import http from './common/http'
import util from './common/util'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		userInfo : {},
		menuList : [],
		systemName : '',
		URL : {
			upload : '/api/xagrid/upload',
		},
		systemList : [],

		allMenu : [],

		pageData : {},

		router : [],

		//存储页面信息，保持页面刷新后的状态。
		pageInfo : {
			systemIndex : 0,
			menuIndex : 0,
			namearr : [],
		},

	},
	getters : {
		userInfo : state => state.userInfo,
		menuList : state => state.menuList,
		systemName : state => state.systemName,
		URL : state => state.URL,
		center : state => state.center,
		city : state => state.city,
		systemList : state => state.systemList,
		pageData : state => state.pageData,
		router : state => state.router,
		pageInfo : state => state.pageInfo,
	},
	mutations: {
		setUserInfo (state, obj) {
		    state.userInfo = obj;
		},
		setSystemList (state, obj) {
	        state.systemList = obj;
	    },
		setMenuList (state, obj) {
	        state.menuList = obj;
	    },
	    setSystemName (state, obj) {
	        state.systemName = obj;
	    },
	    setAllMenuList (state, obj) {
	        state.allMenu = obj;
	    },
	    //存菜单的index
	    setMenuIndex (state, menuIndex) {
	    	state.pageInfo.menuIndex = menuIndex;

	    	const arr = menuIndex.split('_');
	    	const s = state.allMenu[0].children[parseInt(arr[0])];
	    	const m1 = s.children[parseInt(arr[1])];
	    	const m2 = m1.children[parseInt(arr[2])];

	    	const sysname = s.name;
	    	const m1name = m1.name;
	    	const m2name = m2.name;

	    	state.pageInfo.namearr = [sysname, m1name, m2name];
	    	sessionStorage.setItem('pageInfo', JSON.stringify(state.pageInfo));
	    },
	    //存系统的index
	    setMenu (state, menuIndex) {
	        state.menuList = state.allMenu[0].children[menuIndex].children;
	        state.pageInfo.systemIndex = menuIndex;
	        sessionStorage.setItem('pageInfo', JSON.stringify(state.pageInfo));
	    },
	    //设置默认的系统
	    setDefaultMenu (state) {
	    	const index = state.pageInfo.systemIndex;
	    	state.menuList = state.allMenu[0].children[index].children;
	    }, 
	    //设置pageinfo，如果缓存有值，用缓存的值。如果缓存没有值，给缓存付值。
	    setPageInfo (state, obj) {
	    	const p = sessionStorage.getItem('pageInfo');
	    	if(p != null){
	    		state.pageInfo = JSON.parse(p);
	    	}else{
	    		sessionStorage.setItem('pageInfo', JSON.stringify(state.pageInfo));
	    	}
	    },
	},
	actions: {
		async getMenuList ({ commit, dispatch}, para) {

			const res = await http('menuList');

			const result = util.transData(res, 'id', 'pid', 'children');

			let systemList = [];
			result[0].children.forEach((item, index) => {
				systemList.push({
					name : item.name,
					index,
				});
			});

			commit('setAllMenuList', result);
			commit('setSystemList', systemList);
			commit('setDefaultMenu');
		},

	}
})
